package ru.ifmo.croak.impl.remoting.post.team2.client;

import ru.ifmo.croak.api.Message;

import java.io.*;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: yevgeniy
 * Date: 5/23/11
 * Time: 9:09 PM
 * To change this template use File | Settings | File Templates.
 */
public class MessageDumper implements Runnable {
    private ConcurrentLinkedQueue<Message> dumpBuffer;
    private String directoryName;
    private MessageSender messageSender;
    private String name;
    private Logger log;

    public MessageDumper(String name, String directoryName, MessageSender messageSender) {
        this.name = name;
        log = Logger.getLogger(name);
        this.directoryName = directoryName;
        this.messageSender = messageSender;
        File directory = new File(directoryName);
        if (!directory.exists()) {
            log.info("Directory does not exists");
            directory.mkdir();
        }
        BufferedReader in;
        for (File file : directory.listFiles()) {
            if(file.isFile()) {
                if (file.getName().matches("\\.msg")) {
                    try {
                        in = new BufferedReader(new FileReader(file.getAbsolutePath()));
                        Message message = new Message();
                        message.setId(UUID.fromString(in.readLine()));
                        message.setTime(Long.valueOf(in.readLine()));
                        message.setAuthor(in.readLine());
                        String line;
                        while ((line = in.readLine()) != null) {
                            message.setText(message.getText()+"\n" + line);
                        }
                        in.close();
                        messageSender.addMessage(message);
                    } catch (IOException e) {

                    }
                }
            }
        }
    }

    public synchronized void removeMessageFromDump(Message message) {
        File file = new File(directoryName+"/"+message.getId().toString()+".msg");
        if (file != null) {
            file.delete();
        }
    }

    public void addMessage(Message message) {
        dumpBuffer.add(message);
    }

    public void run() {
        try {
            while(true) {
                while (dumpBuffer.isEmpty()) {
                    wait();
                }
                Message message = dumpBuffer.poll();
                try {
                    BufferedWriter out = new BufferedWriter(new FileWriter(directoryName+"/"+message.getId().toString()+".msg"));
                    out.write(message.getId().toString()+"\n");
                    out.write(message.getTime()+"\n");
                    out.write(message.getAuthor()+"\n");
                    out.write(message.getText());
                    out.flush();
                    out.close();
                } catch (IOException iOException) {
                    log.info("MessageDumper "+name+" is falling down. It may be reason of lost messages");
                }
                messageSender.addMessage(message);
            }
        } catch (InterruptedException e) {

        }
    }
}
